import logging
import logging.handlers
from pathlib import Path
import os
import time
from configmanager import CONFIG

def setup_logger():
    """配置并返回日志记录器"""
    log_dir = Path(CONFIG.log.directory)
    log_dir.mkdir(exist_ok=True)
    
    logger = logging.getLogger('proxy_server')
    logger.setLevel(getattr(logging, CONFIG.log.level))
    
    # 清理旧日志文件
    for log_file in log_dir.glob('proxy.log*'):
        if log_file.stat().st_mtime < (time.time() - CONFIG.log.retention_days * 86400):
            log_file.unlink()
    
    # 日志格式
    formatter = logging.Formatter(
        '%(asctime)s - %(levelname)s - %(threadName)s - %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    
    # 文件处理器 - 按天滚动，保留7天
    file_handler = logging.handlers.TimedRotatingFileHandler(
        filename=log_dir / 'proxy.log',
        when='midnight',
        backupCount=CONFIG.log.retention_days,
        encoding='utf-8'
    )
    file_handler.setFormatter(formatter)
    file_handler.setLevel(logging.INFO)
    
    # 控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(formatter)
    console_handler.setLevel(logging.INFO)
    
    logger.addHandler(file_handler)
    logger.addHandler(console_handler)
    
    return logger

# 全局日志记录器
LOGGER = setup_logger()
